import axios from 'axios';

export default class Http {
  constructor(config = {}) {
    this.get = this.get.bind(this);
    this.post = this.post.bind(this);

    this.instance = axios.create(config);

    /**
     * 请求拦截
     */
    this.instance.interceptors.request.use(
      request => {
        // 设置 token
        request.headers.authorization = `Bearer xxx-token`;
        return request;
      },
      error => Promise.reject(error),
    );

    /**
     * 响应拦截
     */
    this.instance.interceptors.response.use(
      response => {
        const { code, message, data } = response.data;
        if (code === 200) {
          return data;
        } else if (code === 401) {
          // 未登录跳转到登录页
        } else {
          return Promise.reject(new Error(message));
        }
      },
      error => Promise.reject(error),
    );
  }

  /**
   * GET 请求
   * @param {String} url 请求地址
   * @param {Object} params 请求参数
   */
  get(url, params) {
    return this.instance.request({ method: 'get', url, params });
  }

  /**
   * POST 请求
   * @param {String} url 请求地址
   * @param {Object} data 请求参数
   */
  post(url, data) {
    return this.instance.request({ method: 'post', url, data });
  }
}
